/*
 * @lc app=leetcode.cn id=124 lang=java
 *
 * [124] 二叉树中的最大路径和
 *
 * https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/description/
 *
 * algorithms
 * Hard (38.39%)
 * Likes:    263
 * Dislikes: 0
 * Total Accepted:    20.1K
 * Total Submissions: 52.2K
 * Testcase Example:  '[1,2,3]'
 *
 * 给定一个非空二叉树，返回其最大路径和。
 *
 * 本题中，路径被定义为一条从树中任意节点出发，达到任意节点的序列。该路径至少包含一个节点，且不一定经过根节点。
 *
 * 示例 1:
 *
 * 输入: [1,2,3]
 *
 * ⁠      1
 * ⁠     / \
 * ⁠    2   3
 *
 * 输出: 6
 *
 *
 * 示例 2:
 *
 * 输入: [-10,9,20,null,null,15,7]
 *
 * -10
 * / \
 * 9  20
 * /  \
 * 15   7
 *
 * 输出: 42
 *
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int sum;
    int max = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        fun(root);
        return this.max;

    }

    int fun(TreeNode root) {
        if(root == null)
            return 0;

        int l = fun(root.left);
        int r = fun(root.right);
        int sum = root.val, res = root.val;
        if(l > 0) {
            sum += l;
            res = sum;
        }

        if(r > 0) {
            sum += r;
            res = Math.max(root.val + r, res);
        }
        this.max = sum > this.max ? sum : this.max;
       // System.out.println(this.max);
        return res;


    }
}
// @lc code=end

